<template>
  <n-form ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
    <n-form-item path="phone">
      <n-input v-model:value="model.phone" clearable placeholder="手机号码" />
    </n-form-item>
    <n-form-item path="password">
      <n-input v-model:value="model.password" clearable type="password" show-password-on="click" placeholder="密码" />
    </n-form-item>
    <n-form-item path="imgCode">
      <n-input v-model:value="model.imgCode" placeholder="验证码，点击图片刷新" />
      <div class="pl-8px">
        <image-verify v-model:code="imgCode" />
      </div>
    </n-form-item>
    <n-form-item path="organizationId">
      <organization-select v-model:value="model.organizationId" />
    </n-form-item>
    <n-space :vertical="true" :size="24">
      <div v-if="false" class="flex-y-center justify-between">
        <n-checkbox v-model:checked="rememberMe">记住我</n-checkbox>
        <n-button :text="true" @click="toLoginModule('reset-pwd')">忘记密码？</n-button>
      </div>
      <n-button
        type="primary"
        size="large"
        :block="true"
        :round="true"
        :loading="auth.loginLoading"
        @click="handleSubmit"
      >
        确定
      </n-button>
    </n-space>
    <other-account v-if="false" />
  </n-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { useAuthStore } from '@/store';
import { useRouterPush } from '@/composables';
import { formRules, getImgCodeRule } from '@/utils';
import { OrganizationSelect, OtherAccount } from './components';

const auth = useAuthStore();
const { login } = useAuthStore();
const { toLoginModule } = useRouterPush();

const formRef = ref<HTMLElement & FormInst>();

const model = reactive({
  phone: '',
  password: '',
  imgCode: '',
  organizationId: null
});

const imgCode = ref('');

const rules: FormRules = {
  phone: formRules.phone,
  password: formRules.pwd,
  imgCode: getImgCodeRule(imgCode),
  organizationId: {
    required: true,
    message: '请选择组织',
    trigger: 'change'
  }
};

const rememberMe = ref(false);

function handleSubmit(e: any) {
  e.preventDefault();
  formRef.value
    ?.validate(async errors => {
      if (!errors) {
        const { phone, password, organizationId } = model;
        login(phone, password, organizationId as any);
      }
    })
    .catch(() => {});
}
</script>

<style scoped></style>
